package com.zmc.third.controller;

import com.zmc.common.annotation.PreventRepeatSubmit;
import com.zmc.common.domain.vo.third.PayRefundVo;
import com.zmc.common.enums.RequestSourceEnum;
import com.zmc.common.utils.R;
import com.zmc.third.application.PayApplicationService;
import com.zmc.third.infrastructure.bean.resp.PayNotifyResp;
import com.zmc.third.infrastructure.bean.vo.PayCodeVo;
import com.zmc.third.infrastructure.bean.vo.PayQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author：zmc
 * @Date：2024/11/8 21:01
 */

@Controller
@RequestMapping("/pay")
public class PayController {

    @Value("${pay.success.page}")
    private String paySuccessPage;

    @Autowired
    private PayApplicationService payApplicationService;

    /**
     * 获取支付渠道(支持：扫码支付、电脑网站支付)
     */
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.WEB)
    @RequestMapping("/channel")
    @ResponseBody
    public R getPayChannel(@RequestBody PayCodeVo vo) {
        return payApplicationService.getPayChannel(vo);
    }

    /**
     * 查询支付结果
     * 查询交易状态不要做任何系统业务逻辑，就算是如果用户支付成功也不要做业务逻辑处理，业务逻辑处理需要再异步回调中处理
     */
    @RequestMapping("/query")
    @ResponseBody
    public R query(PayQueryVo vo) {
        return R.ok(payApplicationService.queryPay(vo));
    }

    /**
     * 支付异步回调结果(为了系统的安全性考虑所有的业务逻辑处理，都需要再异步回调中处理不能再查询交易状态中处理)
     * 调用完成之后你需要返回“success”支付宝，如果不返回支付宝就会定时调用该方法.所以你需要在接收到此方法之后完成一系列您的业务操作然后需要返回“success”字符串
     */
    @PostMapping("/{payType}/notify")
    @ResponseBody
    public String notifyPay(@PathVariable("payType") String payType, @RequestParam Map<String, String> params) {
        return payApplicationService.payNotify(payType, params).getResult();
    }

    /**
     * 申请退款
     */
    @PostMapping("/refund")
    @ResponseBody
    public R refund(@RequestBody PayRefundVo vo) {
        return R.ok(payApplicationService.payRefund(vo));
    }


    @RequestMapping("/success")
    public void paySuccessPage(HttpServletResponse response) throws Exception {
        response.sendRedirect(paySuccessPage);
    }

}
